package com.stenio.fancat.validator;

import com.stenio.fancat.annotation.AuthToken;
import com.stenio.fancat.common.FanCatException;
import com.stenio.fancat.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class TokenValidator implements ConstraintValidator<AuthToken, String> {

    private boolean require = false;

    @Override
    public void initialize(AuthToken constraintAnnotation) {
        require = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean flag = false;

        if(require){
            try {
                flag = TokenUtil.isRightToken(value);
            } catch (FanCatException e) {
                e.printStackTrace();
            }
        }else {
            if (StringUtils.isBlank(value)) {
                flag = true;
            }else {
                try {
                    flag = TokenUtil.isRightToken(value);
                } catch (FanCatException e) {
                    e.printStackTrace();
                }
            }
        }

        return flag;
    }
}
